/*
 * @lc app=leetcode.cn id=92 lang=cpp
 *
 * [92] 反转链表 II
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
  ListNode* reverseBetween(ListNode* head, int left, int right)
  {
    ListNode* dummy = new ListNode(-1, head);
    ListNode* pre = nullptr, *cur, *next, *tail = dummy;
    for (int i = 1; i < left; ++i)
      tail = tail->next;
    cur = tail->next;
    while (left <= right) {
      next = cur->next;
      cur->next = pre;
      pre = cur;
      cur = next;
      ++left;
    }
    tail->next->next = cur;
    tail->next = pre;
    return dummy->next;
  }
};
// @lc code=end
